package cn.wxxyhw.control;

import cn.wxxyhw.entity.Student;
import cn.wxxyhw.mapper.StudentMapper;
import cn.wxxyhw.service.StudentService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * @Author: 洪稳
 * @Date: 2019/7/23
 */
@Controller
public class DispatchServlet {

    @Autowired
    private StudentService studentService;
    /*
    * json数据返回前端时出现乱码情况，在@RequestMapping中加入如下内容：produces = "text/plain;charset=utf-8"
    */
    //@ResponseBody
    @RequestMapping(value = "/test")
    public String test(@RequestParam("name") String name,
                       @RequestParam("schoolId") String schoolId,
                       @RequestParam("addr") String addr,
                       @RequestParam("className") String className,
                       Map<String,Object> map){
        Student student = new Student();
        student.setSchoolId(schoolId);
        student.setName(name);
        student.setAddr(addr);
        student.setClassName(className);
        List<Student> students = studentService.getStudentBySchoolId(student);
        map.put("student",students);
        return "detail";
    }

    /**
     * 获取个人图片
     * @param id 学号
     * @return ok
     */
    @ResponseBody
    @RequestMapping("/image/{id}")
    public String getImage(@PathVariable("id") String id,
                           HttpServletResponse response) {
        synchronized (DispatchServlet.class) {
            FileInputStream fis = null;
            OutputStream os = null;
            try {
                fis = new FileInputStream("/opt/wxxy/" + id + ".jpg");
                os = response.getOutputStream();
                int count = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((count = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                    os.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                fis.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "ok";
        }
    }
}
